import os
import re

from jose import jwt

from views.auth import SECRET_KEY, ALGORITHM


def python_insert_args(args: list, steps=None, step=None):
    args_insert = ''
    for item in args:
        value = item.get('value', '')
        if item['type'] == 'password' and len(value) >= 60:
            value = jwt.decode(value, SECRET_KEY, algorithms=[ALGORITHM])['sub']
            args_insert += '{} = r"{}"'.format(item['id'], value) + '\n'
        elif item['type'] == 'enums':
            args_insert += '{} = r"{}"'.format(item['id'], value) + '\n'
        elif item['type'] == 'bool':
            args_insert += '{} = {}'.format(item['id'], value) + '\n'
        elif item['type'] == 'number':
            args_insert += '{} = {}'.format(item['id'], value) + '\n'
        elif item['type'] == 'one_str':
            args_insert += '{} = "{}"'.format(item['id'], value) + '\n'
        elif item['type'] == 'multi_str':
            args_insert += '{} = r"""{}"""'.format(item['id'], value) + '\n'
        elif item['type'] == 'file':
            raw_path = 'depository' + value.replace('//', '/')
            args_insert += '{} = r"{}"'.format(item['id'], raw_path) + '\n'
        if item.get('from') == 2:
            def get_step(_step_id):
                for _i in steps:
                    if _i['id'] == _step_id:
                        return _i
            prefix_step = get_step(value)
            prefix_tool_id = prefix_step['data']['toolkit']['_id']

            cache_path = ['cache', 'flow']
            raw_cache_path = os.sep.join(cache_path)
            files = list(filter(lambda x: prefix_tool_id in x and x.endswith('.log'), os.listdir(raw_cache_path)))
            if files:
                # 获取最新执行的文件
                latest_file_log = max(files, key=lambda x: int(x[-23:-4]))
                with open(raw_cache_path + os.sep + latest_file_log, 'r') as f:
                    log_content = f.read()
                result = re.findall(item['regular'], log_content)
                if result:
                    result = '\n'.join(result)
            else:
                result = ''
            args_insert += '{} = r"""{}"""'.format(item['id'], result) + '\n'
            print(args_insert)
    return args_insert


def shell_insert_args(args: list):
    args_insert = ''
    for item in args:
        value = item.get('value', '')
        if item['type'] == 'password' and len(value) >= 60:
            value = jwt.decode(value, SECRET_KEY, algorithms=[ALGORITHM])['sub']
            args_insert += "{}='{}'".format(item['id'], value) + '\n'
        elif item['type'] == 'enums':
            args_insert += "{}='{}'".format(item['id'], value) + '\n'
        elif item['type'] == 'number':
            args_insert += '{}={}'.format(item['id'], value) + '\n'
        elif item['type'] == 'one_str':
            args_insert += "{}='{}'".format(item['id'], value) + '\n'
        elif item['type'] == 'multi_str':
            args_insert += "{}='{}'".format(item['id'], value) + '\n'
        elif item['type'] == 'file':
            raw_path = 'depository' + value.replace('//', '/')
            args_insert += "{}='{}'".format(item['id'], raw_path) + '\n'
    return args_insert
